package org.sibframework.sda.ids;

import java.sql.SQLException;

import org.sibframework.sda.SdaFactory;
import org.sibframework.sda.SimpleDataAccess;

public class IdGen<T> {

	Class<T> modelClass = null;
	private long id = 0;
	
	IdGen(Class<T> clas) throws SQLException {
		super();
		this.modelClass = clas;
	}
	
	public synchronized long next() throws SQLException {
		long pk = SdaFactory.getInstance().getMaxPk(modelClass);
		
		//error check;
		if (pk == -1) {
			throw new SQLException("Can't get max id of table " + modelClass.getSimpleName());
		}
		
		//compare with cache
		if (pk > id) {
			id = pk;
		}
		
		return ++id;
	}
}
